local class = require 'middleclass'
require 'util'

Button = class('Button')
function Button:initialize(text, x, y, bw, bh, color)
    self.text = text
    self.bx = x
    self.by = y
    self.normalColor = color or {.5, .45, .35}
    self.hoverColor = {.5, .5, .5}
    self.clickColor = {1, 1, 1}
    self.font = lg.newFont(28)
    lg.setFont(self.font)
    self.tw = self.font:getWidth(text)
    self.th = self.font:getHeight()
    self.bw = bw or 40
    self.bh = bh or 25
    self.tx = self.bx - self.tw / 2 + self.bw / 2
    self.ty = self.by - self.th / 2
    self.ox = 0
    self.oy = self.bh / 2
    self.isHovered = false
    self.isClicked = false
end

function Button:draw(x, y)
    self.bx = x or self.bx
    self.by = y or self.by

    local r, g, b, a = love.graphics.getColor()
    lg.setColor(self.normalColor)
    lg.rectangle('line', self.bx - 1 - self.ox, self.by - 1 - self.oy, self.bw + 2, self.bh + 2)

    if (self.isClicked) then
        lg.setColor(self.clickColor)
        lg.rectangle('fill', self.bx - self.ox, self.by - self.oy, self.bw, self.bh)
    elseif (self.isHovered) then
        lg.setColor(self.hoverColor)
        lg.rectangle('fill', self.bx - self.ox, self.by - self.oy, self.bw, self.bh)
    else
        lg.setColor(self.normalColor)
        lg.rectangle('fill', self.bx - self.ox, self.by - self.oy, self.bw, self.bh)
    end
    lg.setColor(0, 0, 0)
    lg.print(self.text, self.tx, self.ty)
    lg.setColor(r, g, b, a)
    self.isClicked = false
    self.isHovered = false
end

function Button:isHover()
    local mouseX = love.mouse.getX()
    local mouseY = love.mouse.getY()
    if mouseX > self.bx - self.ox and mouseX < self.bx - self.ox + self.bw then
        if mouseY > self.by - self.oy and mouseY < self.by - self.oy + self.bh then
            self.isHovered = true
            return
        end
    end
    self.isHovered = false
end

function Button:isClick()
    if (self.isHovered) then
        if (love.mouse.isDown(1)) then
            self.isClicked = true
        end
    end
end

function Button:onClick(func)
    self.clickFunc = func
end

function Button:update(dt)
    self:isHover()
    self:isClick()
    if self.isClicked and self.clickFunc then
        self:clickFunc(dt)
    end
end
